#include "PNGImage.h"
#include "png.h"
#include <cstdio>
#include <cstdlib>

TEST(PNGImageTests, TestReadWrite)
{
	
	string* filename = new string("testpng.png");
	/*
	FILE *fp = fopen(filename->c_str(), "rb");
	if(!fp)
	{
		//HANDLE ERROR
		cerr << "COULD NOT OPEN FILE: " << filename << endl;
		ASSERT_TRUE(false);
	}
	//initialize memory
	int numberToRead = 8;
	char header[sizeof(char)*numberToRead];
	//read the header & pass to pnglib
	fread(header, sizeof(char), numberToRead, fp);
	bool is_png = !png_sig_cmp((png_byte*)header, 0, numberToRead);
	if(!is_png)
	{
		cerr << "FILE: " << filename << " IS NOT A PNG IMAGE" << endl;
		ASSERT_TRUE(false);
	}
	
	//TODO:  add error handling routines
	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
								NULL, NULL, NULL);
	
	//could not read PNG image, handle error
	if(!png_ptr)
	{
		ASSERT_TRUE(false);
	}
	
	//now the input code
	png_init_io(png_ptr, fp);
	
	//the number of signature bytes read
	png_set_sig_bytes(png_ptr, numberToRead);
	
	//TODO:  SET UP CALLBACK FOR handleUnknownChunk
	
	png_infop info_ptr = png_create_info_struct(png_ptr);
	
	//handle error
	if(!info_ptr)
	{
		png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
		ASSERT_TRUE(false);
	}	
	//read the entire image into memory with no transformations
	png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
	
	//read and store the comments
	int num_text;
	int height = png_get_image_height(png_ptr, info_ptr);
	png_textp TEXT_ARRAY[height];
	png_get_text(png_ptr, info_ptr, TEXT_ARRAY, &num_text);
	
	//get row data
	//png_bytepp rowPointers;	
	//rowPointers = png_get_rows(png_ptr, info_ptr);
		
	//memory copy the text data
	png_textp TEXT_DATA=NULL;
	memcpy((void*)TEXT_DATA, (void*)TEXT_ARRAY, sizeof(png_textp)*height);
	
	//if its null, fail the test
	if(TEXT_DATA == NULL)
	{
		ASSERT_TRUE(false);
	}
	
	//clean up
	png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
	*/
	string* NEWFILENAME = new string("test_output.png");
	PNGImage* pngImage = new PNGImage();
	ASSERT_TRUE(pngImage->initializePNGModel(filename, 
					&TextChunk::readTextChunk(&TextChunk::defaultsFilename)));
	ASSERT_TRUE(pngImage->writeNewImageWithTextChunk(NEWFILENAME));
	/*
	free(TEXT_DATA);
	delete filename;
	delete NEWFILENAME; */
	delete pngImage; 
}